﻿using System.Linq;
using System.Collections.Generic;
using System.Reflection;
using Ue.Core.FileSystems;
using Ue.Eagle.Runtime.FileSystems;

namespace Ue.Eagle.Runtime
{
    /// <summary>
    /// 项目编译器
    /// </summary>
    public interface IBuildManager
    {
        IEnumerable<Assembly> GetReferencedAssemblies();
        bool HasReferencedAssembly(string name);
        Assembly GetReferencedAssembly(string name);
        Assembly GetCompiledAssembly(string virtualPath);
    }

    public class BuildManager : IBuildManager
    {
        private readonly IAssemblyLoader assemblyLoader;
        private readonly IRootFolder rootFolder;

        public BuildManager(
            IRootFolder rootFolder,
            IAssemblyLoader assemblyLoader)
        {
            this.rootFolder = rootFolder;
            this.assemblyLoader = assemblyLoader;
        }

        public IEnumerable<Assembly> GetReferencedAssemblies()
        {
            return System.Web.Compilation.BuildManager.GetReferencedAssemblies().OfType<Assembly>();
        }

        public bool HasReferencedAssembly(string name)
        {
            var assemblyPath = this.rootFolder.Combine("bin", name + ".dll");

            return this.rootFolder.FileExists(assemblyPath);
        }

        public Assembly GetReferencedAssembly(string name)
        {
            if (!this.HasReferencedAssembly(name))
            {
                return null;
            }

            return this.assemblyLoader.Load(name);
        }

        public Assembly GetCompiledAssembly(string virtualPath)
        {
            try
            {
                return System.Web.Compilation.BuildManager.GetCompiledAssembly(virtualPath);
            }
            catch
            {
                return null;
            }
        }
    }
}
